<?php
namespace Home\Controller;
use Common\Controller\HomeController;
/**
* 
*/
class ShopcarController extends HomeController
{
	public function addShopcar(){
		if (IS_AJAX) {
			$id=session('id');//用户id
			$name=session('name');//用户名
			$com_id=I('post.comid',0,'intval');
			//配置购物车数据库字段
			
			$data['user_id']=$id;//用户id
			$data['user_name']=$name;//用户名
			$data['com_num']=I('post.num',0,'intval');//商品数量
			$data['com_id']=$com_id;//商品数量
			//找出商品图片和链接
			$com_img=M('ComImage')->field('com_img_name,com_img_link')->where('com_id='.$com_id)->order('id asc')->find();
			$data['com_img_name']=$com_img['com_img_name'];
			$data['com_img_link']=$com_img['com_img_link'];
			//找出商品关键词和单价
			$com=M('Commodity')->field('com_name,com_discription,com_price,com_store')->where('com_status=1 AND id='.$com_id)->find();
			$data['com_name']=$com['com_name'];
			$data['com_discription']=$com['com_discription'];
			$data['com_price']=$com['com_price'];
			$data['com_store']=$com['com_store'];

			$car_com=M('Shopcar')->field('id')->where("user_id=$id AND com_id=$com_id")->find();
			
			if ($car_com['id']>0) {
				M('Shopcar')->where('id='.$car_com['id'])->save($data);
			}else{
				M('Shopcar')->add($data);
			}
			$data['status']="ok";//状态
			return $this->ajaxReturn($data);
		}
	}
	public function shopcar(){
		// echo '用户ID'.session('id');
		// echo '用户名'.session('name');
		// if (IS_GET) {
		// 	echo '数量'.$num=I('get.num',0,'intval');
		// 	echo '商品ID'.$num=I('get.comid',0,'intval');
			
		// }
		// $id=session('id');//用户id
		// $name=session('name');//用户名
		// $com_num=I('post.num',0,'intval');//商品数量
		// $com_id=I('post.comid',0,'intval');//商品id
		// //商品图片
		// $com_img=M('ComImage')->field('com_img_name,com_img_link')->where('com_id='.$com_id)->order('id asc')->find();
		// print_r($com_img);
		// exit;
		$this->addressinfo=U('Home/Shopcar/addressinfo');
		$this->product=U('Home/Product/product');
		$this->display();
	}
	public function delete(){
		$success=M('Shopcar')->where('id='.I('get.shopid'),0,'intval')->delete();
		if ($success) {
			$this->success('删除成功！',U("Home/Shopcar/shopcar"));
		}else{
			$this->error('删除失败！');
		}
	}

	public function addressinfo(){

		//找出所有的地址
		$name=session('name');
		if(!empty($name)){
			
			$id=M('HomeUser')->field('id')->where("username='{$name}'")->find();
			$id=$id['id'];
		}

		$addresses=M('UserAddress')->where('user_id='.$id)->order('id desc')->select();
		
		if ($addresses) {
			$this->assign('addresses',$addresses);
		}
		
		//获取到选取的付款商品
		if (IS_POST) {
			//逻辑是根据选中商品的id值去所有商品的id中，找到其对应的键值，再根据键值去商品数量中找到对应的数量；最后把选中商品的id和数量对应起来。进行数据更新。
			$shop=I('post.shop',0,'intval');//选中商品的id
			$num=I('post.num',0,'intval');//所有商品的数量
			$id_num=I('post.id_num',0,'intval');//所有商品的id
			// print_r($num)."<br>";
			// print_r($shop)."<br>";
			// print_r($id_num)."<br>";
			
			foreach ($shop as $key => $value) {
				$shop_num[$key]['shop']=$value;
			}
			foreach ($shop_num as $key => $value) {
				foreach ($id_num as $ke => $val) {
					if ($value['shop']==$val) {
						$shop_key[]=$ke;
					}
				}
			}
			foreach ($num as $key => $val) {
				foreach ($shop_key as $k => $value) {
					if ($key==$value) {
						$shop_num[$k]['num']=$val;
					}
				}
			}
			// print_r($shop_num)."<br>";
			// exit;
			//更新购物车数量变化之后的数据库
			foreach ($shop_num as $key => $value) {
				$data['com_num']=$value['num'];
				M('Shopcar')->where('id='.$value['shop'])->save($data);
			}
			//查询选中的商品在数据更新后-的数据
			foreach ($shop_num as $key => $value) {
				$shopcar[]=M('Shopcar')->where('id='.$value['shop'])->select();
			}
			$this->assign('payact',U('Home/Shopcar/payact'));
			$this->assign('addAddress',U('Home/Personcenter/addaddress'));
			$this->assign('shopcar',$shopcar);
		}
		//找出地区的联动下拉框的值
		$regionmodel=M('region');
		$this->states=$regionmodel->where("pid=1")->select();
		$this->areas=$regionmodel->where("pid=2")->select();
		$this->locals=$regionmodel->where("pid=33")->select();
		$this->region=U('Home/Shopcar/region');
		$this->addressact=U('Home/Shopcar/addressact');
		$this->del=U('Home/Shopcar/delete');
		$this->member=U('Home/Shopcar/member');
		$this->display();
	}
	public function payact(){
		//生成订单号
		$id=M('Payorder')->field('id')->select();
		if ($id) {
			//拿出最新的id号
			foreach ($id as $key => $value) {
				$id[$key]=$value['id'];
			}
			rsort($id);
			$payid=$id[0];
			//找到最新的订单号
			$paynum=M('Payorder')->field('order_num')->find();
			//找到定力最后的数字
			$number=substr($paynum['order_num'], strlen($paynum['order_num'])-6,strlen($paynum['order_num']));
			//找到当前时间
			$nowtime=date('YmdHis',time());
			//找到最新订单里面的时间
			$date=substr($paynum['order_num'],7,14);
			//如果时间一样，订单后面的号码加1；不等从100000开始
			if ($nowtime===$date) {
				++$number;
			}else{
				$number=100000;
			}
		}else{
			$number=100000;
		}
		$time=date("YmdHis",time());
		
		$woodnum=$time.$number;
		
		//接受post值
		if (IS_POST) {
			// print_r($_POST);
			$addid=I('post.address_id',0,'intval');
			$address=M('UserAddress')->where('id='.$addid)->find();
			$address_str="";
			$address_str.=$address['address'].' '.$address['username'].' '.$address['email'].' '.$address['postcode'].' '.$address['gender'].' '.$address['phone'].' '.$address['tel'];
			
			
			$data['address_id']=$address_str;
			$comid=I('post.comid',0,'intval');
			$data['message']=I('post.message');
			$data['all_price']=I('post.all_price',0,'intval');
			
			// $data['status']=I('post.status',0,'intval');
			$data['express']=I('post.express');
		}
		$data['user_id']=session('id');
		$data['order_num']=$woodnum;
		$pay_id=M('Payorder')->add($data);
		if ($pay_id) {
			foreach ($comid as $key => $value) {
				//固化商品信息
				$com=M('Shopcar')->field('com_id')->where('id='.$value)->find();
				$com_pay[$key]['com_id']=$com['com_id'];
				$com_pay[$key]['payorder_id']=$pay_id;
			}
			$res=M('ComPayorder')->addAll($com_pay);
			// session('orderid',$pay_id);
			$this->success('提交成功！',U("Home/Shopcar/payply?payid=".$pay_id));
		}else{
			$this->error('提交失败！');
		}
	}
	public function payply(){
		
		// $payid=session('orderid');
		// print_r($pay);
		// exit;
		if (IS_GET) {
			$payid=I('get.payid',0,'intval');
		}
		$pay=M('Payorder')->field('order_num,all_price,id')->where('id='.$payid)->find();
		$this->priceAll=$pay['all_price']+10;
		$this->assign('woodnum',$pay['order_num']);
		$this->assign('order_id',$pay['id']);
		$this->assign('topay_act',U('payNow'));

		//找到用户名和ID
		$name=session('name');
		$this->display();
	}

	public function payNow(){
        layout(false);
        $order_id = I('post.order_id');
        $this->order_pay = I('post.pay');
        session('order_id',$order_id);
        session('order_pay',$this->order_pay);
        if($order_id>0){
            //准备支付数据
            $order = M('Payorder')->find($order_id);
            //连接支付宝
            include THINK_PATH."Library/Org/Alipay/AopSdk.php";
            $alipay = new \AopClient;
            $alipay->gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
            $alipay->appId = C('appId');
            $alipay->rsaPrivateKey = C('rsaPrivateKey');
            $alipay->format = C('format');
            $alipay->charset= C('charset');
            $alipay->signType= C('signType');
            $alipay->alipayrsaPublicKey = C('alipayrsaPublicKey');
            include THINK_PATH."Library/Org/Alipay/Aop/request/AlipayTradePagePayRequest.php";
            $request = new \AlipayTradePagePayRequest();
            $content="{" .
                "    \"out_trade_no\":\"".$order['id']."\"," .
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," .
                "    \"total_amount\":".$order['all_price']."," .
                "    \"subject\":\"购物吧\"," .
                "    \"body\":\"购物吧\"," .
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," .
                "    \"extend_params\":{" .
                "    \"sys_service_provider_id\":\"2016080600177324\"" .
                "    }".
                "  }";
            $request->setBizContent($content);
            $request->setNotifyUrl(U('alipayNotify','',true,true));
            $request->setReturnUrl(U('alipayReturn','',true,true));
			$this->form = $alipay->pageExecute($request); //调用SDK生成表单
			$this->display();
        }else{
            $this->error("参数错误");
        }
    }

    public function alipayReturn(){
        //连接支付宝
        include THINK_PATH."Library/Org/Alipay/AopSdk.php";
        $aop = new \AopClient();
        $alipayrsaPublicKey = C('alipayPublickey');
        $signtype = C('signType');
        $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
        $arr=$_GET;
        $result = $aop->rsaCheckV1($arr, $alipayrsaPublicKey, $signtype);
        if($result){
            // $order_id=$arr['trade_no'];
            // if($order_id){
                $orderModel=M('payorder');
                //开启事务
                $orderModel->startTrans();
                //查询订单
                
                // $order=$orderModel->lock(true)->find($order_id);
                // if($order&&$order['status']==0){
                    //查找商品准备扣除库存
                    // $opModel=M('ComPayorder');
                    // $pModel = M("Commodity");
                    // $products = $opModel->where('payorder_id='.$order_id)->select();
                    // foreach ($products as $key => $product) {
                    //     $re = $pModel->lock(true)->find($product['com_id']);
                    //     if($re&&$re['com_store']>=$product['num']){
                    //         $pModel->stock=$re['com_store']-$product['num'];
                    //         $status = $pModel->where("id={$product['com_id']}")->save();
                    //         if(!$status){
                    //             $orderModel->rollback();
                    //             echo $re['com_name'],"商品库存错误";
                    //         }
                    //     }else{
                    //         $orderModel->rollback();
                    //         echo $re['com_name'],"商品库存不足";
                    //     }
                    // }
                    $data['status']="已付款";
                    $data['payment']=session('order_pay');
                    $order_id=session('order_id');
                    $osStatus = M('payorder')->where("id=".$order_id)->save($data);
                   	
                    if($osStatus){
                        $orderModel->commit();
                        $this->success("支付成功",U('/Home/Personcenter/orderall'));
                    }else{
                        $orderModel->rollback();
                        echo $re['name'],"商品库存错误";
                    }
                // }else{
                //     echo "订单信息错误";
                // }
            // }
        }else{
            echo 'error';
        }
    }
}